package com.masasdani.paypal.controller;

import com.masasdani.paypal.service.PayPalSubscriptionService;
import com.masasdani.paypal.service.PaypalService;
import com.paypal.api.payments.*;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

@Controller
@RequestMapping("/planOrderPaypal/")
public class PaypalPlanOrderController {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private PayPalSubscriptionService payPalSubscriptionService;

	@Autowired
	private PaypalService paypalService;

	public static final String PAYPAL_SUCCESS_URL = "success";
	public static final String PAYPAL_CANCEL_URL = "cancel";
	public static final String PAYPAL_REFUND_URL = "refund/success";

	@RequestMapping(method = RequestMethod.GET)
	public String index(){
		return "OrderIndex";
	}

	/**
	 * 创建自动续费订单
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "createPlanOrder")
	public String createPlanOrder(HttpServletRequest request) {
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal= Calendar.getInstance();
			cal.add(Calendar.DATE,1);
			Date time=cal.getTime();
			String dateString = sf.format(time);
			//UTC时间，第二天早晨9点收取第二次费用
			dateString = dateString + " 09:30:00";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = null;
			try {
				date = sdf.parse(dateString);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
			df.setTimeZone(TimeZone.getTimeZone("UTC"));
			String timestamp = df.format(date);
			System.out.println(timestamp);
			//创建计划
			Plan plan = payPalSubscriptionService.createPlan(request);
			//激活计划
			payPalSubscriptionService.activatePlan(plan.getId());

			System.out.println("plan.getId()："+plan.getId());

			//拉起支付页面
			String url = payPalSubscriptionService.createPlanOrder(plan.getId(), timestamp);

			return url;
		}catch (Exception e){
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 自动续费支付结果失败
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
	public String cancelPay(){
		return "cancel";
	}

	/**
	 * 自动续费支付结果成功
	 * @param token
	 * @param ba_token
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
	public String successPay(@RequestParam("token") String token, @RequestParam("ba_token") String ba_token){
		//用户支付成功后，重定向返回的页面携带的token
		try {
			System.out.println("token："+token);
			String agreementId = payPalSubscriptionService.execOrderplan(token);
			System.out.println("agreementId = " + agreementId);
			System.out.println("PDT通知：交易支付成功回调");
//			log.info("Agreement created with ID " + agreement.getId());
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return "orderSuccess";
	}

	/**
	 * 支付退款并取消订阅
	 * @param agreementId
	 * @param amountToRefund
	 * @return
	 * @throws PayPalRESTException
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_REFUND_URL)
	public String refundPayment(@RequestParam("agreementId") String agreementId, @RequestParam("amountToRefund") double amountToRefund, @RequestParam("saleId") String saleId) throws PayPalRESTException {
		try {
			// 可选：获取取消后的订阅协议状态
			System.out.println("agreementId: " + agreementId);
			Agreement cancelledAgreement = payPalSubscriptionService.cancelledAgreement(agreementId,amountToRefund,saleId);
			System.out.println("Cancelled Agreement State: " + cancelledAgreement.getState());
			if (cancelledAgreement != null) {
				// 成功退款
				log.info("退款成功");
				//修改订单及用户状态
				return "success";
			} else {
				// 退款失败
				log.info("退款失败");
				return "error";
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}





}